﻿using System;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using BrettM.Web.Hosting;

namespace BrettM.Web.Restful
{
    public class RestfulErrorHandler : IErrorHandler 
    {
        public bool CanHandleError(object sender, ErrorEventArgs e)
        {
            return sender is RestHttpApplication ;
        }

        public void OnError(object sender, ErrorEventArgs e)
        {
            if (sender == null) throw new ArgumentNullException("sender");
            if (e == null) throw new ArgumentNullException("e");


            // Create a copy of route data for the error controller, storing a copy of the error in the 
            // route data.
            var routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("exception", e.Exception);
            routeData.Values.Add("action", "InternalServerError");

            var application = sender as RestHttpApplication;

            // Set the response and clear the error
            application.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            application.Server.ClearError();
            // Create an instance of the error controller and execute it
            IController errorController = new ErrorController();
            routeData.DataTokens.Add("Namespaces", new[] { errorController.GetType().Namespace });
            errorController.Execute(new RequestContext(new HttpContextWrapper(application.Context), routeData));
        }
    }
}
